
//记录查询出的所有用户信息
var siteMenuobj=new Array();

//记录点击当前行的用户ID 修改用户信息使用
var siteMenuGridnwxMenuId;

var siteMenuUserId=0;

function siteMenuGridColumnsRenderRolelink(nwxMenuId,sname){
	siteMenuGridnwxMenuId=nwxMenuId;
	showsiteMenuRoleForm(nwxMenuId,sname);
}
function siteMenuGridColumnsRenderdellink(nwxMenuId,sname){
	
	Ext.MessageBox.confirm('信息', '是否确认删除菜单： '+sname+'?', function(btn){
		
		if(btn=='yes'){
			Ext.Ajax.request({
				url:'delAdminSiteMenu.do',
				method:'POST',
				params:{
					ids:nwxMenuId
				},
				success:function(response){
					if(response.responseText=='1'){
						Ext.MessageBox.alert('信息','删除成功！');
						siteMenuGridStore.reload();
					}else{
						Ext.MessageBox.alert('ERROR','删除失败！');
					}
				},
				failure:function(){
					Ext.Msg.alert('ERROR','错误');
				}
			});
		}
	});
}

function siteMenuGridColumnsRenderInfolink(nwxMenuId){
	siteMenuGridnwxMenuId=nwxMenuId;
	if(siteMenuGridnwxMenuId==null)return ;
	showsiteMenuAddForm(2,siteMenuobj[nwxMenuId]);
}

var siteMenuAddWin;
var siteMenuContent=new Ext.form.TextField({
		labelAlign:'right',
		width:390,
		fieldLabel: '菜单标题'
});
var siteMenusPicUrl=new Ext.form.FileUploadField({
		id: 'form-file',
		width:188,
		buttonText: '浏览...',
        emptyText: '选择一张图片',
        fieldLabel: '上传图片',
        name: 'txtpath',
        buttonCfg: {
        	width: 30,
            iconCls: 'upload-icon'
        }
});
var siteMenusUrl=new Ext.form.ComboBox({
		fieldLabel: '点击跳转链接',
		width:155,
        store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectAdminUserUrl.do',
            fields:['sName','nWxUserUrlId'],
            listeners:{
	    		beforeload:function(store,records,options){
	    			store.baseParams = {
						userid:siteMenuUserId
	    			};
	    		}
            }
        }),
        mode:'local',
	    valueField:'nWxUserUrlId',
	    displayField:'sName',
        emptyText:'全部',
        triggerAction:'all',
        selectOnFocus:true
	});
var siteMenunisValid=new Ext.form.Checkbox({
		fieldLabel:'是否有效',
		labelAlign:'right',
		checked:true
});

var siteMenudelPicBtn=new Ext.Button({
		text:'取消上传',
		handler:function(){
			siteMenusPicUrl.reset();
		}
});
var siteMenunOrder=new Ext.form.NumberField({
		labelAlign:'right',
		width:155,
		value:0,
		fieldLabel: '排序号'
});

var siteMenuImage = new Ext.BoxComponent({
//    id: 'imgPosition',  
    //hidden:true,  
    xtype: 'box',  
    width: 120,  
    height: 100,  
    style: '',  
    autoEl: {
        tag: 'img',
        id:"imgPosition",
	 	name:"imgPosition",
        src: '' //指定url路径  
    }  
});

var siteMenuType=new Ext.form.ComboBox({
		fieldLabel:'类型',
		labelAlign:'right',
		width:155,
		editable:false,
        store: new Ext.data.ArrayStore({
            fields: ['value', 'text'],
            data:[
			        [1, '幻灯片'],
			        [2, '菜单']
		        ]
        }),
	    valueField:'value',
	    displayField:'text',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        value:1,
        selectOnFocus:true
	});

//tinfo参数值1 :添加 2:修改
function showsiteMenuAddForm(tinfo,siteMenuJson) {
	
	if(!siteMenuAddWin){
		siteMenuAddform = new Ext.FormPanel({
			fileUpload: true,
		    border: false,
		    labelAlign:'right',
		    frame:true,
		    items: [
		    	{columnWidth:1.0,layout:'column',labelAlign:'right',items:[
		    		{columnWidth:.6,layout:'form',labelAlign:'right',items:[siteMenusPicUrl]},siteMenudelPicBtn
		    	]},
                {layout:'column',items:[
                	 {columnWidth:.65,layout:'form',items:[
                	 siteMenusUrl,siteMenunOrder,siteMenuType,siteMenunisValid
	                ]},
	                {columnWidth:.35,layout:'form',items:[
	                	siteMenuImage
	                ]}
                ]},
            	siteMenuContent
		    ],
		    buttons: [{
		        text: tinfo,
		        handler: function() {
		        	if(this.text=='添 加'){
		        		 siteMenuAddform.getForm().submit({
		                    url: 'saveAdminSiteMenu.do',
		                    method:'POST',
		                    waitMsg: 'Uploading your data...',
		                    params : {
		                    	userid:siteMenuUserId,
		                    	sContent:siteMenuContent.getValue(),
			                   	nWxUserUrlId:siteMenusUrl.getValue(),
			                   	nOrder:siteMenunOrder.getValue(),
			                   	ntype:siteMenuType.getValue(),
			                   	nisValid:siteMenunisValid.checked?1:2
		                    },
		                    success: function(fm, o){
		                    	if(o.result.success=='1'){
		                    		Ext.MessageBox.alert('信息!', '添加成功!');
			                        siteMenuAddform.getForm().reset();
			                        siteMenuAddWin.hide();
			                        siteMenuGridStore.reload();
		                    	}else if(o.result.success=='3'){
		                    		Ext.MessageBox.alert('Error!', '图片格式不正确（仅支持JPG、PNG）!');
		                    	}else if(o.result.success=='4'){
		                    		Ext.MessageBox.alert('Error!', '用户不明确 请选择用户点击查询!');
		                    	}else{
		                    		Ext.MessageBox.alert('Error!', '添加失败!');
		                    	}
		                    },
							failure:function(form, action) {
								Ext.Msg.alert('错误', '添加失败！');
								return ;
							}
		                });
		        	}else if(this.text=='修 改'){
		        		siteMenuAddform.getForm().submit({
		                    url: 'updateAdminSiteMenu.do',
		                    method:'POST',
		                    waitMsg: 'Uploading your data...',
		                    params : {
		                    	sContent:siteMenuContent.getValue(),
			                   	nWxUserUrlId:siteMenusUrl.getValue(),
			                   	nOrder:siteMenunOrder.getValue(),
			                   	nisValid:siteMenunisValid.checked?1:2,
			                   	spicUrl:siteMenusPicUrl.getValue(),
			                   	ntype:siteMenuType.getValue(),
			                   	wxMenuId:siteMenuGridnwxMenuId
		                    },
		                    success: function(fm, o){
		                    	if(o.result.success=='1'){
		                    		Ext.MessageBox.alert('信息!', '修改成功!');
			                        siteMenuAddform.getForm().reset();
			                        siteMenuAddWin.hide();
			                        siteMenuGridStore.reload();
		                    	}else if(o.result.success=='3'){
		                    		Ext.MessageBox.alert('Error!', '图片格式不正确（仅支持JPG、PNG）!');
		                    	}else{
		                    		Ext.MessageBox.alert('Error!', '修改失败!');
		                    	}
		                    },
							failure:function(form, action) {
								Ext.Msg.alert('错误', '修改失败！');
								return ;
							}
		                });
		        	}
		        }
		    },{
		        text: '返 回',
		        handler: function() {
		        	siteMenuAddform.getForm().reset();
		        	siteMenuAddWin.hide();
		        }
		    }]
		});
		
		siteMenuAddWin =new Ext.Window({
		    title: '信息',
		    closeAction: 'hide',
		    width: 600,
		    height: 390,
		    layout: 'fit',
	        resizable: true,
	        modal: true,
	        items: siteMenuAddform,
	        listeners :{
	        	close:function(){
	        		siteMenuAddform.getForm().reset();
	        	}
	    	}
		});
	}
    siteMenuAddWin.show();
    
    if(tinfo==2){
    	siteMenuAddWin.setTitle('信息：'+siteMenuJson.scontent);
    	siteMenuAddform.buttons[0].setText('修 改');
    	
    	if(siteMenuJson.norder!=null)
    		siteMenunOrder.setValue(siteMenuJson.norder);
    	if(siteMenuJson.nisValid!=null)
    		siteMenunisValid.setValue(siteMenuJson.nisValid==1?true:false);
    	if(siteMenuJson.scontent!=null)
    		siteMenuContent.setValue(siteMenuJson.scontent);
    	if(siteMenuJson.nwxUserUrlId!=null)
    		siteMenusUrl.setValue(siteMenuJson.nwxUserUrlId);
		if(siteMenuJson.ntype!=null)
			siteMenuType.setValue(siteMenuJson.ntype);
    	if(siteMenuJson.spicUrl!=null){
    		siteMenusPicUrl.setValue('1');
    		Ext.getDom('imgPosition').src=siteMenuJson.spicUrl==''?'#':siteMenuJson.spicUrl;
    	}
	}else{
		siteMenuAddform.buttons[0].setText('添 加');
		siteMenuAddform.getForm().reset();
		Ext.getDom('imgPosition').src='#';
	}
}

Ext.onReady(function(){
	siteMenuiswriteidb= Ext.get('siteMenuiswriteid').getValue()==1?true:false;
	
	var siteMenuField=new Ext.form.ComboBox({
		fieldLabel:'类型',
		labelAlign:'right',
		editable:false,
        store: new Ext.data.ArrayStore({
            fields: ['value', 'text'],
            data:[
            		[0, '全部'],
			        [1, '幻灯片'],
			        [2, '菜单']
		        ]
        }),
	    valueField:'value',
	    displayField:'text',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        value:0,
        selectOnFocus:true
	});
	
	var adminSiteMenunkey=new Ext.form.ComboBox({
		fieldLabel: '选择用户',
		editable:false,
        store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectAdminUsers.do',
            fields:['nUserId','sName']
        }),
        mode:'local',
	    valueField:'nUserId',
	    displayField:'sName',
        emptyText:'全部',
        triggerAction:'all',
        selectOnFocus:true
	});
	
	var siteMenuSearchBtn=new Ext.Button({
		text:'查询',
		handler:function(){
			siteMenuUserId=adminSiteMenunkey.getValue();
			siteMenusUrl.getStore().reload();
			siteMenuGridStore.load({
				params : {
					start : 0,
					limit : 20,
					'userid':adminSiteMenunkey.getValue(),
					'ntype':siteMenuField.getValue()
				}
			});
		}
	});
	
	var siteMenuSearch=new Ext.Panel({
		height:50,
		region:'north',
		layout:'column',
		frame: true,
		border:false,
		bodyBorder:false,
		items:[
			{columnWidth:.38,layout:'form',labelAlign:'right',items:[adminSiteMenunkey]},
			{columnWidth:.38,layout:'form',labelAlign:'right',items:[siteMenuField]},
			{columnWidth:.2,layout:'form',labelAlign:'right',items:[siteMenuSearchBtn]}
			]		
	});
	
	siteMenuGridStore = new Ext.data.Store({
        autoLoad: false,
        proxy : new Ext.data.HttpProxy({
            url: 'searchAdminSiteMenu.do'
        }),
        baseParams:{
        	'userid':adminSiteMenunkey.getValue(),
        	'ntype':siteMenuField.getValue()
        },
        reader:new Ext.data.JsonReader({
             totalProperty: 'totalSize',
             root:'list'
        },[
        	{name: 'norder',mapping:'norder', type: 'int'},
            {name: 'nuserId',mapping:'nuserId', type: 'int'},
        	{name: 'nisValid',mapping:'nisValid',   type: 'int'},
        	{name: 'nwxMenuId',mapping:'nwxMenuId', type: 'int'},
        	{name: 'scontent',mapping:'scontent', type: 'string'},
        	{name: 'spicUrl',mapping:'spicUrl', type: 'string'},
        	{name: 'ntype',mapping:'ntype', type: 'int'},
        	{name: 'nwxUserUrlId',mapping:'nwxUserUrlId', type: 'int'},
        	{name: 'dcreateTime',mapping:'dcreateTime', type: 'date',
        		convert : function(v) {
        			return new Date(v);
        		}
        	}
        ])
    });
    
    siteMenuGridStore.on("beforeload", function(thiz, options) { 
		thiz.baseParams["ntype"] = siteMenuField.getValue();
		thiz.baseParams["userid"] = adminSiteMenunkey.getValue();
	});
    
    siteMenuAddBtn =new Ext.Button({
		text:'添加',
		hidden:siteMenuiswriteidb,
		handler:function(){
			showsiteMenuAddForm(1,'');
		}
	});
    
    var siteMenuGridBar=new Ext.PagingToolbar({
		store: siteMenuGridStore,
		displayInfo: true,
		pageSize:20,
		displayMsg : '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
		emptyMsg: "没有记录可以显示",
		beforePageText:'当前页码',
		afterPageText:'共{0}页', 
		firstText:'第一页', 
		prevText:'上一页', 
		nextText:'下一页', 
		lastText:'最后一页', 
		refreshText:'刷新当前页',
		items:['-', siteMenuAddBtn]
     });
     
    siteMenuGridColumnsRenderInfo=function(value, cellmeta, record, rowIndex, columnIndex, store){
    	siteMenuobj[record.data.nwxMenuId]=record.json;
    	var linkhtml='';
    	if(siteMenuiswriteidb==false){
	    	linkhtml='<a style="margin-right:20px" onclick="siteMenuGridColumnsRenderInfolink('+record.data.nwxMenuId+')" href="javascript:void(0)">详细 </a>';
	    	linkhtml+='<a onclick="siteMenuGridColumnsRenderdellink('+record.data.nwxMenuId+',\''+record.data.scontent+'\')" href="javascript:void(0)"> 删除</a>';
    	}
    	return linkhtml;
	};
	
	siteMenuGrid = new Ext.grid.GridPanel({
        store: siteMenuGridStore,
        region:'center',
		disableSelection: true,
		border:false,
		frame:true,
		stripeRows:true,
		loadMask :{msg:"数据加载中，请稍等..."},
		layout:'fit',
		viewConfig:{
			forceFit: true,
			scrollOffset:0
		},
        cm:new Ext.grid.ColumnModel([
        	new Ext.grid.RowNumberer(),
            {header: "排序号", width:30, dataIndex: 'norder', sortable: true},
            {header: "内容",flex: 1, dataIndex: 'scontent', sortable: true},
            {header: "类型", width:50,sortable: true,dataIndex: 'ntype',
            	renderer:function(value){
            		if (value == 1) {
			            return '幻灯片';
			        }else{
			        	return '菜单';
			        }
            	}
            },
            {header: "是否有效", width:50,sortable: true,dataIndex: 'nisValid',
            	renderer:function(value){
            		if (value == 1) {
			            return '有效';
			        }else{
			        	return '无效';
			        }
            	}
            },
            {header: "创建时间",flex: 1, dataIndex: 'dcreateTime', sortable: true,renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s')},
            {header: "操作", width:150,align:'center',sortable: true,renderer:siteMenuGridColumnsRenderInfo}
        ]),
        bbar: siteMenuGridBar
    });
    
	 var mainPanel = new Ext.Viewport({
	 	layout:'border',
		renderTo:'siteMenuDIV',
		id:'siteMenuMainPanel',
		items:[siteMenuGrid,siteMenuSearch],
		listeners: {
	        'resize': function(viewport,adjWidth,adjHeight,rawWidth,rawHeight)  {
	          	Ext.getCmp("siteMenuMainPanel").setHeight((document.body.clientHeight - 290) * 0.67);  
			}
    	}
	});
})